package com.huluobo.sign.pages

import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.lib_base.BaseLoadingDialog
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_base.RoutePath
import com.huluobo.lib_base.UIState
import com.huluobo.sign.SignIntent
import com.huluobo.sign.SignViewModel
import com.huluobo.sign.entity.SignEntity
import com.huluobo.sign.entity.SignEntityItem
import com.king.ultraswiperefresh.UltraSwipeRefresh
import com.king.ultraswiperefresh.rememberUltraSwipeRefreshState
import kotlinx.coroutines.launch

/**
 *  Created by LC on 2025/6/2.
 */

@Composable
fun SignListPage(navHostController: NavHostController, vm: SignViewModel = hiltViewModel()) {
    val list = remember {
        SnapshotStateList<SignEntityItem>()
    }

    var isShowProgress by remember {
        mutableStateOf(false)
    }

    //刷新框架的状态
    val state = rememberUltraSwipeRefreshState()
    //当前的页码
    var page by remember {
        mutableStateOf(1)
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnError -> {
                        isShowProgress = false
                        ToastUtils.showLong("获取签到列表失败:${it.msg}")
                        Log.e("TagA", "获取签到列表失败:${it.msg}")
                    }

                    UIState.OnLoading -> {
                        isShowProgress = true
                    }

                    is UIState.OnSuccess<*> -> {
                        isShowProgress = false
                        list.addAll(it.data as SignEntity)
                        list.sortByDescending { item ->
                            item.createTime
                        }
                    }
                }
            }
        }

        vm.sendIntent(SignIntent.GetAllSign("1", "10"))
    })

    //当刷新时,加载的协程
    LaunchedEffect(key1 = state.isRefreshing, block = {
        if (state.isRefreshing) {
            page = 1
            vm.sendIntent(SignIntent.GetAllSign("$page", "10"))
            state.isRefreshing = false
        }
    })

    //当加载更多时,调用的协程
    LaunchedEffect(key1 = state.isLoading, block = {
        if (state.isLoading) {
            page++
            vm.sendIntent(SignIntent.GetAllSign("$page", "10"))
            state.isLoading = false
        }
    })

    if (isShowProgress) {
        BaseLoadingDialog()
    }

    Scaffold(
        bottomBar = {
            Button(
                onClick = {
                    //跳转到签到页面
                    navHostController.navigate(RoutePath.SIGN_COMMIT)
                }, modifier = Modifier
                    .fillMaxWidth()
                    .padding(10.dp)
            ) {
                Text(text = "签到")
            }
        }
    ) {
        Column(
            Modifier
                .padding(it)
                .padding(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp)
        ) {
            BaseTitle(title = "考勤打卡", navHostController = navHostController)
            Spacer(modifier = Modifier.height(10.dp))
            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                val week = TimeUtils.getChineseWeek(System.currentTimeMillis())
                Text(text = "时间$week")
                Text(text = "考勤规则")
            }
            Spacer(modifier = Modifier.height(10.dp))
            UltraSwipeRefresh(state = state, onRefresh = {
                state.isRefreshing = true
            }, onLoadMore = {
                state.isLoading = true
            }) {
                LazyColumn(content = {
                    items(list) { item ->
                        SignItem(signEntityItem = item)
                    }
                }, verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth())
            }
        }
    }
}

@Composable
fun SignItem(signEntityItem: SignEntityItem) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .border(1.dp, Color.LightGray)
            .padding(10.dp), colors = CardDefaults.cardColors(
            containerColor = Color.White
        )
    ) {
        Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
            Text(text = "签到信息")
            Text(text = "经纬度", fontSize = 11.sp, color = Color.LightGray)
            Text(
                text = "经度 : ${signEntityItem.lat} , 维度 : ${signEntityItem.lon}",
                fontSize = 11.sp,
                color = Color.LightGray
            )
            Text(text = "打卡类型 : ${signEntityItem.type}")
            Text(text = "打卡状态 : ${signEntityItem.status}")
            Text(text = "打卡地点 : ${if (signEntityItem.address.isNullOrEmpty()) "八维学校" else signEntityItem.address}")
            Text(text = "打卡时间 : ${signEntityItem.createTime}")

        }
    }
}